
const { to, openLoading, closeLoading, showToast, backParentLoad } = getApp()
const { WORD_ORDER_OPERATION_TYPE } = require('../../../constant/index')
const { updateWorkOrder, queryWorkOrderById } = require('../../../api/workOrder')
Page({
  data: {
    formData: {
      reasonLabel: '',
      operationContent: ''
    },
    orderData: {}
  },

  onLoad() {
    this.getUserDataById()
  },

  async getUserDataById() {
    const params = {
      workOrderId: this.options.workOrderId
    };
    openLoading()
    const [err, data] = await to(queryWorkOrderById(params));
    closeLoading()
    if (!err) {
      this.setData({
        orderData: data
      })
    }
  },

  handleChooseReason() {
    const ressonArray = ['信息填写错误', '问题解决了', '其它']
    wx.showActionSheet({
      itemList: ressonArray,
      success: (res) => {
        this.setData({
          ['formData.reasonLabel']: ressonArray[res.tapIndex]
        })
      }
    })
  },

  handleFieldChange(event) {
    this.setData({
      ['formData.operationContent']: event.detail
    })
  },

  checkValidate() {
    const ressonArray = ['信息填写错误', '问题解决了', '其它']

    const { reasonLabel, operationContent } = this.data.formData
    if (!reasonLabel) {
      showToast('请选择取消原因')
        return false
    }
    if (reasonLabel === ressonArray[2]) {
      if (!operationContent) {
        showToast('请填写具体的取消原因')
        return false
      }
    }

    return true
  },

  async handleSubmit() {
    const isValidate = this.checkValidate()

    if (!isValidate) return

    const { orderData, formData: { reasonLabel, operationContent } } = this.data
    const params = {
      workOrderId: orderData.workOrderId,
      operationType: WORD_ORDER_OPERATION_TYPE.WORK_ORDER_CANCEL,
      operationContent: [reasonLabel, operationContent].filter(item => item).join(','),
    }
    openLoading()
    const [err] = await to(updateWorkOrder(params))
    closeLoading()

    if (!err) {
      showToast({
        message: '提交成功',
        type: 'success',
        mask: true,
        onClose: () => {
          setTimeout(() => {
            backParentLoad(1)
          }, 1000)
        }
      })
    }
  }
})